// pages/connectDev/connectDev.js
var app = getApp()
var common = require("../../../common/common.js")
var BLELocker = require('../../../common/BLELocker.js')
var commonUtil = require('../../../utils/commonUtil');

//常量数据配置
var ConstantData = require('../../../common/constant_data.js')
var colonyBlue = require("../../../pages/index/colony_blue.js")
var statistic = require("../../../pages/index/statistic.js")
var noDepositLease = require("../../../pages/index/no_deposit_lease.js")
var util = require('../../../utils/util.js');
var connectUtil = require('../../../utils/ble-dfu/connect.js');
var newConUtil = require('./newConUtil')
import AudioUtil from '../../utils/AudioUtil';

var systemInfo = wx.getSystemInfoSync()
var baseVer = systemInfo.SDKVersion
const user_id = wx.getStorageSync('user_id')
var rfId = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ruleListy: [],
    depositPop: false,
    retryCount: 0,
    equTypeName: '',
    showMaintPlatform: false,
    showUseOtherMini: false,
    showImage: '',
    platformTipDesc: '',
    //设备使用图示显示为false
    showHelpPicFlg: false,
    //免费时长剩余提醒
    showFreeTipDialog: false,
    showScanTimeoutDialog: false,
    noticeList: [
      '租借中有任何疑问 请联系我们客服',
      '设备租借后请妥善保管，丢失需照价赔偿哦～',
    ],
    openLockRec: '设备连接中，请稍后...',
    // 交易保障标配置
    jybzConfig: {
      pageType: 'goods_detail',
      goodsName: 'e家康护共享轮椅',
      goodsImg: 'https://www.ejiakanghu.cn/images/mini_tip/home_ad_top.png',
      goodsPrice: '租金￥0.00元起',
      align: 'between',
      spaceSize: 12,
      bannerStyle: {
        fontSize: 'mini',
        fontOpacity: 'gray',
      },
    },
    connectType: '租借',
    miniImg: {
      chair_insert_style: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/chair_insert_style.jpg',
      kaoyou: 'http://minio.ejiakanghu.cn/lbb-erp/temp/编组72x(1)_1695181564139.png',
      short_box: 'http://minio.ejiakanghu.cn/lbb-erp/temp/编组72x(2)_1695182071464.png',
      long_box: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/long_box.png',
      temp_time_card: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/temp_time_card.jpg',
      use_tip_img_1: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-1.png',
      use_tip_img_2: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-2.png',
      use_tip_img_3: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-3.png',
    },
    showStat: {
      //收费规则
      rule: false,
      //蓝牙/网关连接
      connect: false,
      //隐藏连接状态
      hideLoad: false,
      //按钮连接
      btncon: false,
      //租借成功显示
      leasesuc: false,
      //蓝牙IOS系统授权引导
      bleauthIos: false,
      //蓝牙安卓系统授权引导
      bleauthAndroid: false,
      //蓝牙安卓系统可跳转去打开提示
      bleauthAndroidToSet: false,
      //蓝牙应用权限设置
      bleauthAppToSet: false,
      //蓝牙小程序授权设置
      bleMiniAuthToSet: false,
      //蓝牙应用的定位权限设置
      locationAuthAppToSet: false,
      //IOS系统定位权限提示
      locationIosTip: false,
      //安卓系统定位权限提示
      locationAndroidTip: false,
      //失败提示
      failTip: false,
      //归还成功
      backsuc: false,
      //归还成功后立马租借提示
      backSucToLease: false,
      //结果信息显示
      resultTip: false,
      //展示结果说明信息
      resultDesc: '',
      //苹果蓝牙系统设置视频
      bleIosSysSetVideo: false,
    },
    statVal: {
      //查询免押订单
      queryNoDeposit: "queryNoDeposit",
      //免押成功后开锁
      noDepositOpen: "noDepositOpen",
      //蓝牙搜索中
      discover: "discover",
    },
    read: true,
    showRules: true,
    rulePic: null,
    images: [
      'https://img0.baidu.com/it/u=1411230536,3153397530&fm=26&fmt=auto',
      'https://img2.baidu.com/it/u=3788886525,2387163296&fm=253&fmt=auto&app=120&f=JPEG?w=1203&h=800',
      'https://img1.baidu.com/it/u=2521468805,52921477&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500',
      'https://img2.baidu.com/it/u=2700842424,180930865&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=338'
    ],
    bleIosSysSetHtml: `
        <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">请您将手机蓝牙打开，开锁更快哦！</p></div>
          <div><p style="padding: 0px 20px; color:#595959;">向下轻扫屏幕右上方边缘，打开【控制中心】</p></div>
          <div><p style="padding: 0px 20px; color:#595959;">点击蓝牙图标，开启蓝牙功能</p></div>
          <div style="width:100%;text-align::center;margin-top:15px;"><img src="https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705469917354135552.gif" style="height:167px; display: block;margin:0 auto;"/></div>
        `,
    bleIosSysSetHtml13: `
        <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">第1步:请您将微信蓝牙权限打开</p></div>
          <div style="width:100%;text-align::center;margin-top:15px;"><img src="https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705471744283906048.png" style="height:167px; display: block;margin:0 auto;"/></div>
          <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;margin-top:15px;">第2步:重新启动微信App，扫码使用</p></div>
        `,
    bleIosSysSetHtml2: `
        <div style="padding: 15px 20px;display:inline-block;vertical-align:middle;"><img src="https://www.ejiakanghu.cn/images/mini_tip/dot_tip.png" style="float:left;" /><p style="margin:auto;float:left;font-weight: bold;margin-left:10px;padding-top:2px;">您好像还没有尝试打开，跟着我一起哦</p></div>
        <img src="https://www.ejiakanghu.cn/images/mini_tip/ble_ios_sys_set2.png" style="width:100%; height:auto; display: block;"/>
      `,
    bleAndroidSysSetHtml: `
          <p style="padding: 15px 20px; font-weight: bold;">1、打开设置（通常为小齿轮图标）</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_sys_set.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>
          <p style="padding: 15px 20px; font-weight: bold;">2、根据图示打开系统的蓝牙权限</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_sys_ble.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>          
    `,
    bleauthAndroidToSetHtml: `
         <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">请您将手机蓝牙打开，开锁更快哦！</p></div>
         <div><p style="padding: 0px 20px; color:#595959;">向下轻扫屏幕，打开【控制中心】</p></div>
         <div><p style="padding: 0px 20px; color:#595959;">点击蓝牙图标，开启蓝牙功能</p></div>
         <div style="width:100%;text-align::center;margin-top:15px;"><img src="https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705471383892529152.gif" style="height:260px; display: block;margin:0 auto;"/></div>        
    `,
    locationIosToSetHtml: `
        <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">请您将手机定位打开,开锁更快哦！</p></div>
        <div><p style="padding: 0px 20px; color:#595959;">打开【设置】</p></div>
        <div><p style="padding: 0px 20px; color:#595959;">找到【隐私与安全性】，打开定位服务</p></div>
        <div style="width:100%;text-align::center;margin-top:15px;"><img src="https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705474134064107520.gif" style="height:150px; display: block;margin:0 auto;"/></div>        
    `,
    locationAndroidSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">下滑屏幕点亮位置权限图标</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_sys_location.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    locationAndroidAppToSetHtml: `
          <p style="padding: 15px 20px; font-weight: bold;">1.打开设置</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_app_auth_set.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>
          <p style="padding: 15px 20px; font-weight: bold;">2.设置定位权限为"仅在使用中允许"</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_app_localtion_set.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>          
    `,
    locationIosAppToSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">设置位置权限为"使用APP期间"</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/ios_app_location.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    bleIosAppToSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">根据图示打开蓝牙权限"</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/ios_app_ble.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    blueMiniToSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">要去设置小程序蓝牙权限为"仅在使用小程序期间"</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_mini_blue_set.png?v=1.0" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    locationAppToSetHtml: '',
    depositAutoBack: false,
    isScanBack: false,
    refund: 0,
    userInfoStr: '',
    wxScore: 600,
    leaseBtnShow: false,
    selBindUserId: 0, //选择的绑定的用户id
    isReturn: false,
    modal: {
      modal_show: false
    },
    //支付押金按钮是否可点击，true可以点击，false不可以点击
    payDepositBtnStatus: true,
    //用户手机信息
    phoneInfo: '',
    openLockStat: false,
    bleIosRetryBtnName: '开启后，点击重试',
    //是否点击去查看协议 
    isToViewProtocol: false,
    //是否跳转到租借成功页面
    isToTipBackSucPage: false,

    // 新弹框
    isReturnTip: '',
    isContinueLease: '您是还要继续租借吗？',
    secondSureLeaseState: false,
    checked: false,
    sureState: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    leaseShow.pageThat = this
    bleAuthShow.pageThat = this
    bleFailShow.pageThat = this
    connectShow.pageThat = this
    conTimer.pageThat = this
    connectUtil.connectShowFunc = connectShow
    connectUtil.setConShowViewCallback(this.conShowInfo)
    app.globalData.gatewayConTimeout = 30000
    app.globalData.gatewayUnlockTimeout = 15000
    app.globalData._that = this
    app.globalData.newConThat = this
    app.globalData.conTimer = conTimer
    let that = this
    that.data.colonyConFail = 0
    //用户无归还记录且有押金/免押
    that.data.userStatDirectLease = 2
    that.data.tipOpenLockOverFlg = false
    that.data.connectShow = connectShow
    that.data.leaseShow = leaseShow
    that.data.bleAuthShow = bleAuthShow
    that.data.bleFailShow = bleFailShow
    that.data.systemInfo = systemInfo
    that.data.phoneInfo = systemInfo.brand + systemInfo.model
    let qrc = unescape(options.qrc)
    let type = options.type
    this.data.depositAutoBack = options.depositAutoBack
    this.data.isScanBack = options.isScanBack
    let systeminfo = wx.getStorageSync('systeminfo')
    console.log('systeminfo------------>', options, systeminfo)
    let boxHeight = systeminfo.windowHeight * 2 * 0.85 > 700 ? 700 : systeminfo.windowHeight * 2 * 0.85
    let windowHeight = systeminfo.windowHeight * 2 - boxHeight
    let nextHeight = windowHeight - 282
    this.setData({
      userInfoStr: 'U' + user_id + '-wx' + ConstantData.CONSTATNT_DATA.MINI_VERSION,
      wxScore: options.wxScore,
      connectType: options.connectType,
      windowHeight: windowHeight,
      nextHeight: nextHeight,
      isScanBack: this.data.isScanBack
    })
    this.data.qrc = qrc
    this.data.type = type
    if (wx.getStorageSync('exitLogin')) {
      loginAuth(this)
    }
    this.getPileState()
  },
  //点击扫码还
  scanBackManual() {
    let that = this    
    //扫码还
    that.getPileState()
  },
  //根据桩获取用户信息处理状态信息
  getPileState() {
    let that = this
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    let cont_to_rent = wx.getStorageSync("cont_to_rent")
    that.data.showFreeTipFlg = false
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/order/2/scanCode',
        method: 'get',
        header: header,
        data: {
          mac: that.data.qrc,
          isSecond: cont_to_rent ? cont_to_rent : '',
          isScanBack: that.data.isScanBack == 'true' ? 1 : 0
        },
        success: function (res) {
          that.setData({
            newScanRes: res
          })
          that.sanInfoHandle(res, that)
        },
        fail: function (res) {
          getApp().hideLoading()
          console.log("根据qrc获取mac名称请求失败", res)
          that.data.scanningCode = false;
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          bleFailShow.modalMsgShow()
          that.setData({
            loading_show: false,
            modal: {
              modal_show: true,
              desc: '请重新扫码-' + ConstantData.err_type.qrc_mac_fail,
              confirm: true
            }
          })
          that.recordBlueConnectError(ConstantData.err_type.qrc_mac_fail, 'modalErr--qrc=' + that.data.qrc + ';res:' + JSON.stringify(res));
        },
        complete() {
          getApp().hideLoading()
        }
      })
    })
  },
  //处理扫码接口返回的数据
  sanInfoHandle: function (res, that) {
    console.log('信息=>>>', res, that.data.isScanBack)
    if (res.data.code == '200001') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '无效的mac',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '无效的mac' + JSON.stringify(res));
      return
    } else if (res.data.code == '200002') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '蓝牙未与桩绑定',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '蓝牙未与桩绑定' + JSON.stringify(res));
      return
    } else if (res.data.code == '200003') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '非法设备编号',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '非法设备编号' + JSON.stringify(res));
      return
    } else if (res.data.code == '200004') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '轮椅未在桩上',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '轮椅未在桩上' + JSON.stringify(res));
      return
    } else if (res.data.code == '200005') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '无该设备类型',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '轮椅未在桩上' + JSON.stringify(res));
      return
    } else if (res.data.code == '100001') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '用户不存在',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '用户不存在' + JSON.stringify(res));
      return
    } else if (res.data.code == '900001') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '微信免押单号不存在',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '用户不存在' + JSON.stringify(res));
      return
    } else if (res.data.code == '900004') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '未使用的微信免押不存在',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '未使用的微信免押不存在' + JSON.stringify(res));
      return
    } else if (res.data.code == '900003') {
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '微信支付分下单请求失败',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.scan_code, '微信支付分下单请求失败' + JSON.stringify(res));
      return
    }
    let pileState = ''
    if (res.data.result.isReturn) { //是否归还
      pileState = 0
    } else if (!res.data.result.isPay) { //不归还且无押金/免押
      pileState = 1
    } else if (res.data.result.isPay) { //不归还且有押金/免押
      pileState = 2
    }



    //要连接的设备蓝牙标识
    let macId = res.data.result.macId;
    let isExtBlueName = res.data.result.blueName && res.data.result.blueName.indexOf("DK") != -1;
    that.data.curBlueName = isExtBlueName ? res.data.result.blueName : "DK" + macId;
    that.data.mac = macId
    that.data.conMac = macId;
    if (res.data.result.bleDevId) {
      that.data.wxDeviceId = res.data.result.bleDevId
    } else {
      that.data.wxDeviceId = macId ? newConUtil.getBleDevId(macId) : null
    }
    //是否可以网关连接
    that.data.isGatewayFirstCon = res.data.result.hpIsColony == 1 && res.data.result.colonyIsUsing == 0 && res.data.result.colonyIsExists == 1;
    that.data.isColonyCon = that.data.isGatewayFirstCon
    //非扫码还且返回为1 则为工作人员
    let isWorker = that.data.isScanBack != 'true' && res.data.result.isReturn == 1 && res.data.result.isWorker == 1
    that.setData({
      newIsReturn: res.data.result.isReturn,
      pileState: pileState,
      isWXScore: res.data.result.isWXScore, //免押状态
      rst: res.data.result.rst,
      pageType: res.data.result.pageType,
      orderCode: res.data.result.orderCode,
      eqtTypeId: res.data.result.eqtTypeId,
      isWorker: isWorker,
    })


    if (pileState == 2 || pileState == 0 || that.data.isScanBack == 'true') {
      var nophone = app.getUserLoginNoPhone();
      if (nophone == null || nophone == undefined || nophone == 1) {
        that.toWxLogin()
        return
      }
    }

    if ((res.data.result.isReturn == 1 || res.data.result.isReturn == 2) && res.data.result.isWorker != 1) {
      that.data.isScanBack = 'true'
      //用户需要归还
      newConUtil.getDevIdAndConnect(that.data.qrc);
      return
    }

    var systemInfo = wx.getStorageSync('systeminfo');
    var isCouldNoDeposit = util.isCouldNoDeposit(systemInfo);
    var isAllowNoDeposit = isCouldNoDeposit && res.data.result.wxNoDeposit == 1;
    console.log("-----isAllowNoDeposit=", isAllowNoDeposit);
    if(res.data.result.rst == 5 && res.data.result.desc.indexOf('其他用户租借中') != -1) {
        let desc = res.data.result.desc
        leaseShow.resultShow(desc ? desc : '其他用户租借中，稍后重试')
        that.recordBlueConnectError(ConstantData.err_type.scan_other_using , '其他用户租借中')
        return
    }
    //判断是否有未支付订单
    if (res.data.result.rst == 4 || res.data.result.rst == 5) {
      let rentInfo = {};
      rentInfo.backTime = res.data.result.backTime;
      rentInfo.borrowTime = res.data.result.openTime;
      rentInfo.costTime = res.data.result.timeLenStr;
      rentInfo.deposit = res.data.result.deposit;
      rentInfo.orderCode = res.data.result.orderCode;
      rentInfo.rent = res.data.result.rent;
      rentInfo.noPayTitle = res.data.result.noPayTitle;
      rentInfo.priceLabel = res.data.result.priceLabel;
      rentInfo.orderType = res.data.result.orderType;
      rentInfo.inCycleLeaseTimeLen = res.data.result.inCycleLeaseTimeLen || '';
      rentInfo.inCycleRecordInfoList = res.data.result.inCycleRecordInfoList || [];
      rentInfo.depositBackSuc = res.data.result.isAutoRefund;
      wx.redirectTo({
        url: '../../../pages/index/no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
      }) //0718mark--跳转到支付租金页面
      return
    }
    //扫码归还
    if (that.data.isScanBack == 'true') {
      that.setData({
        ruleList: res.data.result.ruleList,
        leaseMaxPriceStr: res.data.result.leaseMaxFeeStr,
        pricePreferential: res.data.result.pricePreferential,
        equDeposit: res.data.result.deposit,
        equTypeName: res.data.result.tname
      })
      newConUtil.getDevIdAndConnect(that.data.qrc, that.data.type);
      return
    }
    if (res.data.result.CloseDoorTip && !that.data.skipCloseReminder) {
      // mark: 关门提前提醒
      let continueLeaseBtnLeft = false
      let contintueLeaseBtnName = '确定'
      let cancelBtnName = '取消'
      let tipContent = res.data.result.closeDoorTip
      leaseShow.beforeLeaseTipShow(continueLeaseBtnLeft, contintueLeaseBtnName, cancelBtnName, tipContent)
      that.setData({
        skipCloseReminder: true
      })
      return
    }
    if (res.data.result.rst == 13) {
      getApp().hideLoading()
      let errType = ConstantData.err_type.open_lock_13;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2280')
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: res.data.result.errInfo ? res.data.result.errInfo : '当前时间不可租借' + errType,
          confirm: true
        }
      })
      return;
    }
    if (res.data.result.rst == -102) {
      let errType = ConstantData.err_type.open_lock_102;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2289')
      var desc = res.data.result.errInfo ? res.data.result.errInfo : "设备维护中,请换其它桩租赁";
      if (desc == '已经关门,请在营业时间使用') {

      }
      bleFailShow.modalMsgShow()
      that.setData({
        showImage: desc == "设备维护中,请换其它桩租赁" ? '../../image/maint_state.png' : '../../image/close_men.png',
        modal: {
          modal_show: true,
          desc_mini: "(" + that.data.phoneInfo + "-" + errType + ")",
          desc: desc,
          confirm: true,
          desc_center: true
        }
      })

      that.recordBlueConnectError(errType, "开锁:设备维护中,请扫描其他设备,-102")
      return
    }
    if (res.data.result.rst == -138) { //当前设备被预约
      getApp().hideLoading()
      let errType = ConstantData.err_type.open_lock_13;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2280')
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: '当前设备已被预约,请换一台设备租赁。' + errType,
          confirm: true
        }
      })
      that.recordBlueConnectError(errType, "当前设备已被预约,请换一台设备租赁,-138")
      return;
    }
    if (res.data.result.rst == 2) { //同类设备只准租一个,提示用户归还的时候也需要扫一下二维码
      let errType = ConstantData.err_type.open_lock_2;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2214')
      if (res.data.result.leaseNoBackInfo) {
        //未归还的
        if (that.data.pt == 'noback' || (res.data.result.eqId && res.data.result.eqId != res.data.result.leaseNoBackInfo.equId)) {
          getApp().hideLoading()
          bleFailShow.modalMsgShow()
          that.setData({
            modal: {
              modal_show: true,
              desc_mini: errType,
              showOrderbtn: true,
              desc: "您有一台设备正在租借中！我们不支持同时租2个以上设备哦，请将前一台设备归还可继续租借。", // + data.leaseNoBackInfo.equId + "，这个L" + data.leaseNoBackInfo.equId + "轮椅锁在哪个桩位上，就扫哪个桩位玻璃面板上大的二维码就可以归还成功了",
              confirm: true,
              desc_center: true
            }
          })
        } else {
          console.log("跳转到未归还页面--------------------------------》")
          wx.navigateTo({
            url: '../../../pages/index/no_back_tip/no_back_tip?orderCode=' + res.data.result.orderCode + 'equId=' + res.data.result.leaseNoBackInfo.equId + "&positions=" + res.data.result.leaseNoBackInfo.positions + "&hospitalName=" + res.data.result.leaseNoBackInfo.hospitalName,
          })
        }
      } else {
        leaseShow.resultShow('很抱歉,您有未归还的' + res.data.result.tName) // mark: 很抱歉,您有未归还的设备
      }
      return
    }

    let cont_to_rent = wx.getStorageSync("cont_to_rent")
    //判断异常开锁5分钟内是否扫的同一台桩(扫码租赁流程)/ 已归还(归还到扫码时间小于10分钟的判断)
    if (res.data.result.pageType == 0) {
      wx.removeStorageSync("cont_to_rent")
    } else if (res.data.result.pageType == 1) { //异常开锁没有点击重试的展示
      that.setData({
        orderCode: res.data.result.orderCode,
        equId: res.data.result.eqId,
        ruleList: res.data.result.ruleList
      })
      wx.setStorageSync('equId', res.data.result.eqId)
      that.setData({
        retryCount: 1
      })
      bleFailShow.openFailTipShow('')
      that.recordBlueConnectError('pageType' + res.data.result.pageType, "异常开锁:显示重试租借按钮")
      return
    } else if (res.data.result.pageType == 2) { //异常开锁点击重试之后的展示
      that.setData({
        orderCode: res.data.result.orderCode,
        equId: res.data.result.eqId,
        ruleList: res.data.result.ruleList
      })
      wx.setStorageSync('equId', res.data.result.eqId)
      that.setData({
        retryCount: 2
      })
      bleFailShow.openFailTipShow('')
      that.recordBlueConnectError('pageType' + res.data.result.pageType, "异常开锁:显示联系客服")
      return
    } else if (res.data.result.pageType == 3 && !cont_to_rent) { //使用时长大于5分钟且归还到扫码小于10分钟
      conTimer.clearConTimer()
      that.hideAllShow()
      that.setData({
        showStat: {
          showReturn: true,
          resultTip: true,
          returnShowOrderBig: true,
          smalllLease: true,
          resultDesc: '您租借的设备已归还成功，如果您要继续租借，请重新扫码租借～',
          resultSecondDesc: '',
        }
      })
      that.recordBlueConnectError('pageType' + res.data.result.pageType, "继续租借:归还时间较短，重新扫码")
      return
    } else if (res.data.result.pageType == 4 && !that.data.markContinue) { //异常开锁使用时长小于5分钟且归还到扫码小于10分钟
      conTimer.clearConTimer()
      that.hideAllShow()
      that.setData({
        showStat: {
          showReturn: true,
          resultTip: true,
          returnShowOrderSmall: true,
          bigLease: true,
          resultDesc: '您租借的设备已归还成功!',
          resultSecondDesc: '',
        }
      })
      that.recordBlueConnectError('pageType' + res.data.result.pageType, "继续租借:异常开锁继续租借")
      return
    } else {
      wx.removeStorageSync("cont_to_rent")
    }
    // let deposit = res.data.result.deposit?.toString()?.split('.')

    //没有押金、没有免押
    if (that.data.pileState == 1) {
      that.setData({
        isAllowNoDeposit: isAllowNoDeposit,
        toPayDeposit: !isAllowNoDeposit,
        equId: res.data.result.eqId,
        ruleList: res.data.result.ruleList,
        leaseMaxPriceStr: res.data.result.leaseMaxFeeStr,
        pricePreferential: res.data.result.pricePreferential,
        equDeposit: res.data.result.deposit,
        equTypeName: res.data.result.tname
      })
      wx.setStorageSync("no_pay_deposit", 1);
      leaseShow.chargeRuleShow()
    } else if (that.data.pileState == 2) { //有押金或者免押
      that.setData({
        isAllowNoDeposit: isAllowNoDeposit,
        ruleList: res.data.result.ruleList,
        leaseMaxPriceStr: res.data.result.leaseMaxFeeStr,
        pricePreferential: res.data.result.pricePreferential,
        equDeposit: res.data.result.deposit,
        equTypeName: res.data.result.tname
      })
      newConUtil.getDevIdAndConnect(that.data.qrc, that.data.type);
    } else if (that.data.pileState == 0) { //有未归还订单走归还
      newConUtil.getDevIdAndConnect(that.data.qrc, that.data.type);
    }
  },
  changeChecked() {
    const vm = this
    vm.setData({
      checked: !vm.data.checked,
      sureState: false
    })
  },
  checkboxChange: function (e) {
    this.data.checkedVal = e.detail.value
    this.setData({
      checked: !this.data.checked,
      sureState: false
    })
  },

  prevent() {},

  returnIndex: function () {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

  isSureContinueLease: function () {
    this.setData({
      secondSureLeaseState: true,
      checked: false,
      sureState: false
    })
  },

  secondSureLease: function () {
    if (!this.data.checked) {
      this.setData({
        sureState: true
      })
    } else if (this.data.checked) {
      this.setData({
        sureState: false,
        secondSureLeaseState: false,
        isReturn: false
      })
      this.continueToLease()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    let showParams = that.data.checkPayStatusInterval + ';avoid:' + that.data.avoidorpay + ';pileState:' + that.data.pileState + ';loginFlag:' + app.globalData.loginFlag + ';isScanBack:' + that.data.isScanBack
    console.log('show=>>>', showParams)
    setTimeout(() => {
      that.recordBlueConnectError(ConstantData.err_type.new_con_index_show, '新连接页onShow:' + showParams);
    }, 100)

    if (that.data.showStat.resultTip && that.data.showStat.showReturn) {
      console.log("扫码归还成功提示页面，onShow不做改动")
      return
    }

    //开锁结束弹框提示
    if (that.data.tipOpenLockOverFlg === true) {
      that.data.tipOpenLockOverFlg = false
      leaseShow.openLockOverTip()
      return
    }
    //检查是否为支付押金蓝牙未打开的显示
    if (that.data.avoidorpay == 'pay_ble') {
      leaseShow.chargeRuleShow()
      that.toPayDeposit()
      that.data.avoidorpay = ''
      return
    }
    if (that.data.avoidorpay == 'nodeposit_ble') {
      leaseShow.chargeRuleShow()
      that.data.avoidorpay = ''
      wx.showModal({
        title: '是否继续免押租借?',
        content: '',
        complete: (res) => {
          if (res.cancel) {

          }
          if (res.confirm) {
            that.toNoDepositLease()
          }
        }
      })
      return
    }
    if (that.data.isScanBack == 'true') {      
      that.scanBackManual()
      return
    }
    //判断是否登录页面登录后过来的
    if (app.globalData.loginFlag && (that.data.pileState == 0 || that.data.pileState == 2 || that.data.isScanBack == 'true')) {
      app.globalData.loginFlag = ''
      that.getPileState()
      return
    } else if (that.data.pileState == 0 || that.data.pileState == 2 || that.data.isScanBack == 'true') {
      var nophone = app.getUserLoginNoPhone();
      if (nophone == null || nophone == undefined || nophone == 1) {
        wx.navigateBack({
          delta: 1
        })
        return
      }
    }
    //点击押金登录后直接调起付款页面/免押页面
    if (app.globalData.loginFlag && that.data.pileState == 1) {
      app.globalData.loginFlag = ''
      if (that.data.avoidorpay == 'avoid') {
        leaseShow.chargeRuleShow()
        that.toNoDepositLease()
      } else if (that.data.avoidorpay == 'pay') {
        that.toPayDeposit()
      }
      return
    }
    this.data.isToViewProtocol = false
    this.data.isToTipBackSucPage = false
    clearTimeout(this.data.hideDisConTimer)
    clearTimeout(that.data.queryNoDepositTimer)
    if (that.data.checkPayStatusInterval) {
      leaseShow.chargeRuleShow()
    }
    clearInterval(that.data.checkPayStatusInterval);
    that.data.checkPayStatusInterval = null
    commonUtil.getMiniSetting(baseVer)
    systemInfo = wx.getSystemInfoSync()
    baseVer = systemInfo.SDKVersion
    let platform = systemInfo.platform.toLowerCase()
    that.setData({
      locationAppToSetHtml: platform == 'ios' ? that.data.locationIosAppToSetHtml : that.data.locationAndroidAppToSetHtml
    })

    if (that.data.showUnlock) {
      connectShow.successConnect()
    }
    let devIsCon = app.globalData.devConnected;
    console.log("conDevPage onShow :", devIsCon, app.globalData.isOpenLock)
    if (devIsCon && app.globalData.isOpenLock) {
      noDepositLease.getLeaseNoDepositInfo(app.globalData.appOnShowData, that, undefined, that.data.pileState);
    }
  },
  //展示收费规则，免押取消时使用
  showLeaseRule() {
    leaseShow.chargeRuleShow()
  },

  //重试连接
  retryCon: function (e) {
    let that = this
    console.log("retryCon---->", e)
    let clickBtnType = that.data.clickLeaseBtn
    setTimeout(function () {
      that.recordBlueConnectError(ConstantData.err_type.page_hide, '重试连接:' + clickBtnType);
    }, 1000)


    if (that.data.clickLeaseBtn == 'nodeposit') {
      that.toNoDepositLease()
      return
    }
    if (that.data.clickLeaseBtn == 'deposit') {
      that.toPayDeposit()
      return
    }

    if (that.data.isScanBack == 'true') {
      that.getPileState()
      return
    }

    let conType = e.currentTarget.dataset.contype

    let miniVideoIsOk = commonUtil.validateMiniVideoApi()
    if (conType == 'bleIosSys') {
      this.setData({
        bleIosSysSetVideo: miniVideoIsOk,
        bleIosSysSetHtml: that.data.bleIosSysSetHtml2,
        bleIosRetryBtnName: "我已开启，重试",
      })
    }
    newConUtil.getDevIdAndConnect(this.data.qrc, this.data.type);
  },
  /**
   * // mark: 查看小视频 
   */
  viewMniVideo: function (e) {
    let videoid = e.currentTarget.dataset.videoid
    wx.openChannelsActivity({
      finderUserName: 'sphM5c55kSJZjX2',
      feedId: videoid,
      fail: function (err) {
        console.log("视频号视频打开失败:", err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this
    that.recordBlueConnectError(ConstantData.err_type.page_hide, '连接页面隐藏');
    //防止用户切换程序，再回来继续流程导致失败
    if (that.data.canRetry85) {
      that.data.canRetry85 = false;
      wx.reLaunch({
        url: '/pages/index/index',
      })
      return
    }

    if (this.data.isWXScore == 1) {
      conTimer.clearConTimer()
    }
    if (this.data.isToTipBackSucPage) {
      conTimer.clearConTimer()
    }
    if (!this.data.openLockStat && !app.globalData.isOpenLock) {
      let isConnected = app.globalData.devConnected
      if (!this.data.isToViewProtocol && app.globalData.isConnecting === false) {
        this.data.hideDisConTimer = setTimeout(function () {
          BLELocker.disconnect('condev183');
          if (isConnected && !that.data.isToTipBackSucPage) {
            wx.reLaunch({
              url: '../../../pages/index/index',
            })
          }
        }, 35000)
      }
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.isConnecting = false
    app.globalData.isOpenLock = false
    app.globalData.isUpgradeing = false
    this.data.openLockStat = false
    clearTimeout(this.data.hideDisConTimer)
    clearTimeout(this.data.queryNoDepositTimer)
    clearInterval(this.data.checkPayStatusInterval);
    BLELocker.disconnect('condev96')
    this.recordBlueConnectError(ConstantData.err_type.page_unload, '连接页退出');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // mark: 收费规则协议是否勾选
  proCheckChange: function (e) {
    // const values = e.detail.value
    // if (values.length > 0) {
    //   this.setData({
    //     read: true
    //   })
    // } else {
    //   this.setData({
    //     read: false
    //   })
    // }
    this.setData({
      read: e.detail
    })
  },

  //隐藏全部显示提示模块
  hideAllShow: function () {
    this.setData({
      showStat: {
        //收费规则
        rule: false,
        //蓝牙/网关连接
        connect: false,
        //按钮连接
        btncon: false,
        //租借成功显示
        leasesuc: false,
        //蓝牙IOS系统授权引导
        bleauthIos: false,
        //蓝牙安卓系统授权引导
        bleauthAndroid: false,
        //蓝牙安卓系统可跳转去打开提示
        bleauthAndroidToSet: false,
        //蓝牙应用权限设置
        bleauthAppToSet: false,
        //蓝牙小程序授权设置
        bleMiniAuthToSet: false,
        //蓝牙应用的定位权限设置
        locationAuthAppToSet: false,
        //IOS系统定位权限提示
        locationIosTip: false,
        //安卓系统定位权限提示
        locationAndroidTip: false,
        //失败提示信息
        failTip: false,
        //归还成功
        backsuc: false,
        //归还成功后立马租借提示
        backSucToLease: false,
        //结果信息显示
        resultTip: false,
        //展示结果说明信息
        resultDesc: '',
      },
      modal: {
        modal_show: false
      },
    })
  },

  cleanTimer: function () {
    conTimer.clearConTimer()
  },
  // mark: 获取蓝牙授权显示对象
  getBleAuthShowObj: function () {
    return bleAuthShow
  },
  // mark: 获取连接显示对象
  getConnectShowObj: function () {
    return connectShow
  },
  getBleFailShowObj: function () {
    return bleFailShow
  },
  conShowInfo: function (stat) {
    if (stat == 'auth_mini_ble') {
      bleAuthShow.showBleMiniToSet()
    }
  },

  //点击去打开系统蓝牙权限
  toSetSysBle: function () {
    wx.openSystemBluetoothSetting({
      success(res) {
        console.log("打开系统蓝牙配置", res)
      }
    })
  },
  //点击去打开应用的权限
  toSetAppAuth: function () {
    wx.openAppAuthorizeSetting({
      success(res) {
        console.log(res)
      }
    })
  },
  //去设置小程序权限
  toSetMiniAuth: function () {
    wx.openSetting({
      success(res) {
        console.log(res.authSetting)
        getApp().globalData.miniAuthSetting = res.authSetting
      }
    })
  },
  //弹框取消
  onCancelDialog1: function () {
    this.setData({
      showFreeTipDialog: false
    });
  },

  onConfirmDialog1: function () {
    this.setData({
      showFreeTipDialog: false
    });
  },

  onConfirmDialog3: function () {
    this.setData({
      showScanTimeoutDialog: false
    });
    this.returnIndex()
  },
  //查看使用图示
  viewHelpPic: function () {
    let that = this
    this.setData({
      showHelpPicFlg: !that.data.showHelpPicFlg
    })
  },


  /**
   * 处理扫码从服务获取设备信息
   */
  handleConDevRes: function () {
    let that = this
    let res = that.data.conDevRes
    console.log("处理扫码获取的设备信息:", res)
    if (res.data.extParams && res.data.extParams.lockType) {
      that.setData({
        lockType: res.data.extParams.lockType
      })
    }
    that.recordBlueConnectError(ConstantData.err_type.qrc_mac_suc, 'getDevIdAndConnect macId=' + (res.data ? res.data.macId : 'null'));
    //扫码后获取到的连接的mac地址
    that.data.conMac = res.data ? res.data.macId : "";
    that.data.conBlueName = res.data ? res.data.extParams.blueName : "";
    app.globalData.conBlueVer = res.data ? res.data.extParams.blueVer : "";

    that.startConnect(res);
  },
  //开始进行蓝牙连接
  startConnect: function (res) {
    var that = this;
    //取消重试
    let netErr = app.handleRes(res, that);
    if (netErr) {
      that.data.scanningCode = false;
      that.setData({
        loading_show: false
      })
      return
    }
    if (res.data.isBindPhone == 0) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'scan',
        loading_show: false
      });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      that.data.scanningCode = false;
      return;
    }
    that.setData({
      phoneAuthStatus: false,
      phoneAuthBtt: ''
    });
    app.globalData.curConHid = null;
    if (res.data.hid) {
      that.setData({
        pile_id: res.data.hid
      })
      app.globalData.curConHid = res.data.hid;
      wx.setStorageSync('pileId', res.data.hid);
      that.data.pile_type = res.data.hpVer && res.data.hpVer.indexOf('长') != -1;
    }
    app.globalData.isLeaseCon = false;
    app.globalData.isAllowUpgrade = false;
    app.globalData.isBeforeLeaseUpgrade = false;
    app.globalData.allowUpgradeOtherMac = false;
    app.globalData.isPayUpgrade = false;
    app.globalData.isLockUpgrade = false;
    app.globalData.otherMacs = [];
    that.data.isFirstUseNewConLeaseFlg = false;
    that.data.isSend98Cmd = false;
    that.data.canRetry85 = false;

    if (res.data.extParams) {
      that.data.conDevExtParams = res.data.extParams;
      app.globalData.isAllowUpgrade = res.data.extParams.isAllowUpgrade;
      app.globalData.lastDriveVer = res.data.extParams.lastDriveVer;
      app.globalData.isBeforeLeaseUpgrade = res.data.extParams.isBeforeLeaseUpgrade;
      app.globalData.isPayUpgrade = res.data.extParams.isPayUpgrade;
      app.globalData.isLockUpgrade = res.data.extParams.isLockUpgrade;
      app.globalData.allowUpgradeOtherMac = res.data.extParams.allowUpgradeOtherMac ? res.data.extParams.allowUpgradeOtherMac : false;
      app.globalData.otherMacs = res.data.extParams.otherMacs ? res.data.extParams.otherMacs : [];
      //是否第一次是用新的蓝牙连接方式
      that.data.isFirstUseNewConLeaseFlg = res.data.extParams.isFirstUseNewConLeaseFlg ? res.data.extParams.isFirstUseNewConLeaseFlg : false;
      //是否发送98命令
      that.data.isSend98Cmd = res.data.extParams.isSend98Cmd ? res.data.extParams.isSend98Cmd : false;
      //网关连接超时的时长。默认20秒超时
      app.globalData.gatewayConTimeout = res.data.extParams.gatewayConTimeout ? res.data.extParams.gatewayConTimeout : 20000;
      //网关开锁超时的时长,默认15秒超时
      app.globalData.gatewayUnlockTimeout = res.data.extParams.gatewayUnlockTimeout ? res.data.extParams.gatewayUnlockTimeout : 15000;
      //网关连接失败后多长时间内使用蓝牙重试连接，默认为5分钟内再次扫码可使用蓝牙连接
      app.globalData.gatewayFailBleConTime = res.data.extParams.gatewayFailBleConTime ? res.data.extParams.gatewayFailBleConTime : 30000;
      //蓝牙连接失败后多长时间内使用网关重试连接，默认为5分钟内再次扫码可使用网关连接
      app.globalData.gatewayBleFailConTime = res.data.extParams.gatewayBleFailConTime ? res.data.extParams.gatewayBleFailConTime : 30000;
    }



    //清空定时器
    app.clearTimeoutTimer();
    //清空秘钥
    that.data.blepwd = '';

    app.globalData.startConTime = new Date().getTime();
    that.data.newConFlg = res.data.newConFlg;

    //连接的调用不允许进行升级的操作
    app.globalData.isBeforeLeaseUpgrade = false;
    app.globalData.isLeaseCon = true;
    //扫完码拿到数据执行连接的过程
    that.executeConnect(res);
  },

  //执行蓝牙连接
  executeConnect: function (res) {
    var that = this;
    //清空选择的设备类型
    that.setData({
      selTypeList: [],
    })
    //连接前去除95重试标记
    that.data.retry95Flg = false;
    let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
    let errType = '';
    let user_no_back = wx.getStorageSync('user_no_back');
    if (res.data.rst == 0 || (res.data.rst == 6 && user_no_back) || res.data.rst == 10) {
      var hpStat = res.data.hpStat;
      if (hpStat && hpStat != 0 && hpStat != 1) {
        // var desc = res.data.desc ? res.data.desc : "维护中,请使用其他设备";
        if (user_no_back) {
          errType = ConstantData.err_type.qrc_maintain_back;
          var desc = "归位桩维护中,如您确定设备已锁在桩上拉不下来,请联系客服处理";
          var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
          var contact = true;
          var confirm = false;
        } else {
          errType = ConstantData.err_type.qrc_maintain_rent;
          var desc = res.data.desc ? res.data.desc : "归位桩维护中,请换其它桩租赁";
          var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
          var contact = false
          var confirm = true
        }
        bleFailShow.modalMsgShow()
        //归位桩存在问题
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: desc,
            desc_mini: desc_mini,
            open_location_show: false,
            retryConnect: false,
            retry95: false,
            confirm: confirm,
            contact: contact
          }
        })
        that.recordBlueConnectError(errType, 'modalErr:归还失败');
        that.data.scanningCode = false;
        return;
      }

      var name = res.data.macId;
      if (name == null || name == '') {
        console.log("根据qrc获取mac名称为空")
        errType = ConstantData.err_type.qrc_mac_null;
        bleFailShow.modalMsgShow()
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: '请重新扫码-' + errType,
            confirm: true
          }
        })
        that.recordBlueConnectError(errType, 'modalErr:获取mac为空');
        that.data.scanningCode = false;
        return
      }
      var deviceId = res.data.deviceId

      let isExtBlueName = that.data.conBlueName && that.data.conBlueName.indexOf("DK") == -1;
      let conBlueName = isExtBlueName ? that.data.conBlueName : "DK" + name;
      that.setData({
        loading_show: true,
        loading_desc: '开始连接...',
        agentLeaseSelStatus: false,
        showModalStatus: false,
        wxDeviceId: deviceId, //数据库存储的公众号获取的设备id
        curBlueName: conBlueName,
        isNoRfidOpen: res.data.isNoRfidOpen,
        isJudgeInsertSwitch: res.data.judgeInsertSwitch,
        isBackChairStatus: res.data.backStat,
        curIsDirectCon: res.data.curIsDirectCon
      })

      setTimeout(function () {
        that.data.scanningCode = false;
      }, 1000);

      app.globalData.isAllowBroadcastBack = res.data.isAllowBroadcastBack;

      //蓝牙集群节点判断处理
      //是否存在蓝牙节点
      var colonyIsExists = res.data.colonyIsExists;
      //集群节点是否在使用中0未占用,1被占用
      var colonyIsUsing = res.data.colonyIsUsing;
      //是否直接使用蓝牙节点连接
      var hpIsColony = res.data.hpIsColony;
      that.data.hpIsColony = hpIsColony;
      //是否可直接使用节点
      var colonyIsDirectUse = hpIsColony == 1 && colonyIsUsing == 0 && colonyIsExists == 1;

      console.log("是否直接网关连接:", hpIsColony, colonyIsUsing, colonyIsExists, colonyIsDirectUse);

      let firstConFail = colonyBlue.isBleFailGatewayCon();
      console.log("是否首次蓝牙连接失败:", firstConFail);
      //是否在连接失败后使用
      var colonyIsFailUse = hpIsColony == 2 && colonyIsUsing == 0 && colonyIsExists == 1;
      if (colonyIsFailUse && firstConFail) {
        colonyIsDirectUse = true;
        that.data.colonyConFail = 0
      }

      that.data.noBackEqId = res.data.extParams.noBackEqId;
      //网关连接失败后5分钟内扫码，改用蓝牙连接
      let isBleCon = colonyBlue.isGatewayFailBleCon();
      console.log("是否首次网关连接失败:", isBleCon);
      if (!isBleCon && colonyIsDirectUse && that.data.colonyConFail < 3) {
        //开锁前判断是否是蓝牙集群的连接
        that.data.mac = name
        that.data.colonyIsExists = colonyIsExists
        common.storeGatewayClientType();
        console.log("开始直接连接蓝牙集群---->");
        //直接使用蓝牙集群连接
        colonyBlue.connectDev(name, that);
        return;
      }

      if (that.data.pt == 'blue_tip') {
        that.data.pt = '';
      }

      //非网关的使用wxmini
      common.storeWxClientType(that);
      //进行蓝牙连接
      that.data.timeout95RetryFlg = true; //连接后95超时可以进行一次重连
      that.data.retryCon = false; //刚开始还没有进行重试点击
      newConUtil.connectBLEDevice(conBlueName);
    } else if (res.data.rst == 6) { //共享陪护床
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: that.data.conDevExtParams && that.data.conDevExtParams.close_tip ? that.data.conDevExtParams.close_tip : "当前时间不可租借",
          confirm: true
        }
      })
      that.data.scanningCode = false;
    } else if (res.data.rst != 10) {
      errType = ConstantData.err_type.qrc_mac_rst;
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: '请重新扫码-' + errType,
          confirm: true
        }
      })
      that.data.scanningCode = false;
      console.log("根据qrc获取mac请求返回值非0：" + res.data.rst)
      that.recordBlueConnectError(errType, 'modalErr--qrc=' + that.data.qrc + '--' + res.data.rst);
    }

  },
  // mark: 检查连接的蓝牙相关权限
  bleConAuthCheck: function (isCheckLocation) {
    //第一使用蓝牙连接，检查蓝牙连接权限
    let isAuth = commonUtil.validateBleAuth()
    console.log("蓝牙权限校验结果:", isAuth)
    if (isAuth == 'sys_ble_android') {
      //系统蓝牙未打开跳转到对应页面
      bleAuthShow.showAndroidToSettingBle()
      return 1
    } else if (isAuth == 'sys_ble_ios') {
      bleAuthShow.showIosSetBleTip()
      return 1
    } else if (isCheckLocation) {
      if (isAuth == 'sys_location') {
        //跳转到系统定位权限        
        if (systemInfo.platform == 'ios') {
          //苹果系统
          bleAuthShow.showIosSysLocationSetting()
        } else {
          bleAuthShow.showAndroidSysLocationSetting()
        }
        return 1
      } else if (isAuth == 'wx_location') {
        bleAuthShow.showAppLocationSetting()
        return 1
      }
    } else if (isAuth == 'wx_ble') {
      bleAuthShow.showAppBleSetting()
      return 1
    } else if (isAuth == 'mini_ble') {
      bleAuthShow.showBleMiniToSet()
      return 1
    }
    return 0
  },

  clickBeeBanner() {
    wx.navigateToMiniProgram({
      appId: this.data.beeBannerConfig.appId,
      path: this.data.beeBannerConfig.path,
      success(res) {
        console.log('【小蜜蜂广告跳转】跳转成功：' + JSON.stringify(res))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30002, '租借成功-小蜜蜂底部广告', 'success')
      },
      fail(error) {
        console.log('【小蜜蜂广告跳转】跳转失败：' + JSON.stringify(error))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30002, '租借成功-小蜜蜂底部广告', 'fail')
      }
    })
  },

  toViewNoDepositProtocol: function () {
    this.data.isToViewProtocol = true
    wx.navigateTo({
      url: '../../../pkgBak/pages/help/protocol/wx_no_deposit/wx_no_deposit',
    })
  },

  toViewLeaseProtocol: function () {
    this.data.isToViewProtocol = true
    wx.navigateTo({
      url: '../../../pkgBak/pages/help/lease/lease',
    })
  },
  //手动开锁
  openLockTo() {
    let that = this
    if (that.data.curContIsBle) {
      //判断蓝牙是否连接
      if (!app.globalData.devConnected) {
        // that.recordBlueConnectError(errType, '点击开锁时蓝牙断开');
        leaseShow.resultShow("设备连接已断开，请重新扫码租借!")
        return
      }
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    that.setData({
      conLeftSeconds: 0
    })
    newConUtil.leaseEquipment(true)
  },
  getRules: function (rfId) {
    let that = this
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/order/2/rule',
        method: 'post',
        header: header,
        data: {
          rfid: rfId,
        },
        success: function (res) {
          console.log('222=>>', res)
          that.setData({
            ruleList: res.data.result.ruleList,
            leaseMaxPriceStr: res.data.result.leaseMaxFeeStr,
            pricePreferential: res.data.result.pricePreferential,
          })
        },
        fail: function (res) { // mark: 请求open_lock接口失败
          console.log('接口请求失败')
          wx.showToast({
            title: '网络异常请重试',
          })
          leaseShow.netFail("网络异常，请重新扫码租借")
        },
      })

    })
  },
  //无设备异常开锁情况处理信息
  noDeviceUnblank: function (rfId, mac, costTime) {
    var that = this
    //服务端接口存在没有上传的数据为空
    if (!rfId) {
      //将接收到95数据的赋值
      rfId = that.data.rfId;
    }
    if (!mac) {
      //将扫码时获取的mac赋值
      mac = that.data.conMac;
    }
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/order/2/scanCode/rfid',
        method: 'post',
        header: header,
        data: {
          rfid: rfId,
          mac: mac,
        },
        success: function (res) {
          console.warn('开锁异常处理----', rfId, mac, res)
          if (res.data.code == 200) {
            that.setData({
              orderCode: res.data.result.orderCode
            })
            if (res.data.result.isReturn == 1) {
              newConUtil.openOrReturnEquitment(rfId, mac, costTime)
            } else {
              if (res.data.result.pageType == 0) {
                newConUtil.openOrReturnEquitment(rfId, mac, costTime)
              } else if (that.data.isScanBack == 'true') {
                newConUtil.openOrReturnEquitment(rfId, mac, costTime)
              } else if (res.data.result.pageType == 1 && that.data.isScanBack != 'true') { //异常开锁没有点击重试的展示
                conTimer.clearConTimer()
                that.setData({
                  retryCount: 1
                })
                bleFailShow.openFailTipShow('')
                return
              } else if (res.data.result.pageType == 2 && that.data.isScanBack != 'true') { //异常开锁点击重试之后的展示
                conTimer.clearConTimer()
                that.setData({
                  retryCount: 2
                })
                bleFailShow.openFailTipShow('')
                return
              }
            }
          } else {
            leaseShow.netFail("接口请求错误，请重新扫码租借")
          }
        },
        fail: function (res) { // mark: 请求open_lock接口失败
          console.log('接口请求失败')
          leaseShow.netFail("网络异常，请重新扫码租借")
        }
      })

    })
  },

  //开锁
  openLock: function (e) { // mark: 免押租借/交押金租借
    var that = this
    //验证登录
    var nophone = app.getUserLoginNoPhone();
    if (nophone == null || nophone == undefined || nophone == 1) {
      that.setData({
        avoidorpay: 'avoid'
      })
      that.toWxLogin()
      return
    }
    if (!that.data.read) {
      wx.showToast({
        title: '请勾选我已阅读'
      })
      return
    }
    that.data.bleDepositPaySuc = false;
    if (that.data.pileState == 1 && !that.data.selBindUserId) {
      app.globalData.devConnected = true,
        app.globalData.isOpenLock = true
      wx.showLoading({
        title: '加载中...',
        mask: true
      });
      app.executeRequest(function (header) {
        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/order/2/wxPayScore',
          method: 'post',
          header: header,
          data: {
            mac: that.data.qrc
          },
          success: function (res) {
            console.log('1111=>>>>', res)
            if (res.data.code == 200) {
              that.setData({
                isWXScore: 1
              })
              connectShow.clickLeaseFirstShow()
              noDepositLease.toWxNoDepositLeasePage(res.data.result.noDepositInfo, res.data.result.outOrderCode, that);
            } else {
              wx.showToast({
                title: '支付分请求失败',
                icon: 'error',
                duration: 2000
              })
            }
          },
          fail: function (res) {
            that.recordBlueConnectError(ConstantData.err_type.deposit_wxPayScore_fail, "获取免押信息失败" + JSON.stringify(res))
            leaseShow.resultShow('服务器忙,请重新扫码 Z' + that.data.wxHid)
          },
          complete() {
            getApp().hideLoading()
          }
        })
      })
      return
    }
    if (that.data.curContIsBle) {
      //判断蓝牙是否连接
      if (!app.globalData.devConnected) {
        leaseShow.resultShow("设备连接已断开，请重新扫码租借!")
        return
      }
    }

    if (this.data.isAllowNoDeposit && !this.data.noDepositFail) {
      //允许免押
    } else if (!this.data.isPayDeposit) {
      //非免押且未支付押金,弹去支付押金的框
      //交押金租赁
      leaseShow.chargeRuleShow()
      return;
    }

    if (that.data.openLockLeaseOptStatus == false) {
      console.log("租赁中")
      return
    }
    that.setData({
      openning_show: true,
      openning_desc: '开始请求租赁...',
      showModalStatus: false,
      mapShowStatus: true,
      loading_show: false,
      openLockLeaseOptStatus: false,
      bindUserListStatus: false,
      payDepositStat: false
    })

    that.recordBlueConnectError(ConstantData.err_type.deposit_create_order, "用户点击租赁,开始请求租赁-" + that.data.rfId)
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    //进行租赁
    newConUtil.leaseEquipment();

  },

  /**
   * 继续租借
   */
  continueToLease() {
    var that = this;
    //继续租赁   
    //将结果值改为正常，用户继续租赁
    that.data.conDevRes.data.rst = 0
    //处理返回数据并调用蓝牙连接
    that.handleConDevRes()
  },
  /**
   * 继续租借
   */
  afterGetDataContinueToLease() {
    //继续租赁   
    this.sanInfoHandle(this.data.newScanRes, this)
  },

  send85Command: function () {
    var that = this
    clearInterval(that.data.checkPayStatusInterval)
    that.data.openLockLeaseOptStatus = false;
    that.setData({
      loading_show: false,
      openning_show: true,
      openning_desc: '设备正在开锁',
      openLockStat: true
    })
    let connected = getApp().globalData.devConnected;

    if (app.globalData.conBlueVer && app.globalData.conBlueVer == 'om-phy-1.0') {
      that.recordBlueConnectError(ConstantData.err_type.data_76_send, '开始发送phy开锁:' + connected);
      //one more 陪护椅锁开锁指令
      BLELocker.oneMorePhyBleUnlock();
      return;
    }

    if (that.data.isColonyCon) {
      console.log("蓝牙网关开锁处理---->");
      //蓝牙集群连接的
      colonyBlue.openLock(that.data.mac, that);
      that.data.isColonyCon = false;
      return;
    }

    if (that.data.lockSelTypeData) {
      that.recordBlueConnectError(ConstantData.err_type.data_76_send, '开始发送76:' + connected);

      //发送直行锁命令
      let doorNumArr = that.data.lockSelTypeData.selDoorNumSet;
      if (!doorNumArr || doorNumArr.length == 0) {
        that.recordBlueConnectError(ConstantData.err_type.data_76_fail, "门号信息为空")
      } else {
        that.data.lockSelTypeData = null;
        that.send76Command(doorNumArr[0]);
      }
      return;
    }
    that.recordBlueConnectError(ConstantData.err_type.data_85_send, '开始发送85:' + app.globalData.devConnected);
    //是否正在开锁中
    app.globalData.isOpenLock = true;
    setTimeout(function () {
      that.start85Timer();
      BLELocker.send85Command(function (isSuccess) {
        if (isSuccess == false) {
          that.clear85Timer();
          //重试开锁
          that.retry85('auto');
          let failDesc = app.globalData.devConnected + ";retry85Auto:" + that.data.rfId;
          that.recordBlueConnectError(ConstantData.err_type.data_85_send_fail, (that.data.isRedirectOpenLockFlg ? "redirect:" : "开始开锁-fail") + failDesc);
        } else {
          that.recordBlueConnectError(ConstantData.err_type.data_85_send_suc, (that.data.isRedirectOpenLockFlg ? "redirect:" : "开始开锁-suc") + that.data.rfId)
        }
      })
    }, 500);

  },
  send75Command: function (params) {
    var that = this;
    //发送75命令获取信息
    BLELocker.send75Command(function (isSuccess) {
      if (isSuccess == false) {
        if (params == '00') {
          newConUtil.connectBLEDevice(that.data.curBlueName)
        } else {
          wx.showModal({
            showCancel: false,
            title: '温馨提示',
            content: '通信失败,请扫码重试',
            success(res) {}
          })
        }
      } else if (isSuccess == "recevieTimeout") {
        newConUtil.handleStatus(BLELocker.Status.bleRecive75Timeout);
      }
    }, params);
  },

  start85Timer: function () {
    let that = this;
    that.clear85Timer();
    that.setData({
      openLockLeftSeconds: 20
    })
    that.data.timer_85_seconds = setInterval(() => {
      if (!app.globalData.devConnected && that.data.isRetry85) {
        that.setData({
          openning_show: false
        })
        //蓝牙断开
        that.clear85Timer();
        BLELocker.stop85Back1Timeout();
        BLELocker.stop85Back2Timeout();
        //重试开锁
        that.retry85('auto');
      } else if (that.data.openLockLeftSeconds == 0) {
        let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
        let descMini = pile_id + '-' + ConstantData.err_type.data_85_send_timeout;
        statistic.noEjectDialog(that, descMini, '自动重试开锁未弹出');
        that.recordBlueConnectError(ConstantData.err_type.data_85_timer, '20秒的85计时器计时结束，弹出未弹出提示')
        return
      }
      that.setData({
        openLockLeftSeconds: that.data.openLockLeftSeconds - 1
      })
    }, 1000)
  },
  /*开锁成功之后的回调*/
  clear85Timer: function () {
    let that = this;
    clearInterval(that.data.timer_85_seconds);
    that.data.timer_85_seconds = null;
  },

  /**
   * 重试95
   */
  retry95() { // mark: 重试95
    console.log("重试读取95数据----")
    let that = this
    if (that.data.trying) {
      return
    }
    that.data.trying = true
    setTimeout(() => {
      that.data.trying = false
    }, 3000)
    console.log("重试读取95数据----aaa")
    connectShow.read();
    console.log("重试读取95数据----bbb")
    that.data.retry95Flg = true;
    this.send95Command();
  },

  send95Command: function () { // mark: 重试发送95命令
    var that = this;
    //重试发送95的标记
    that.data.retry95Flg = true;
    if (!that.data.randomNum) {
      that.data.randomNum = app.globalData.boxRandomNumKey;
    }
    if (!getApp().globalData.devConnected) {
      that.handleConDevRes()
    } else if (that.data.randomNum) {
      BLELocker.send95Command(function (isSuccess) {
        if (isSuccess == false) {
          newConUtil.connectBLEDevice(that.data.curBlueName)
        } else if (isSuccess == "recevieTimeout") {
          newConUtil.handleStatus(BLELocker.Status.bleRecive95Timeout);
        }
      })
      return;
    } else {
      leaseShow.resultShow('请重新扫码租借!')
    }
  },

  //展示连接状态信息  
  showStatInfo: function (stat) {
    let that = this
    console.log("展示租赁相关状态信息:", stat, that.data.statVal.queryNoDeposit)
    if (stat == that.data.statVal.queryNoDeposit) {
      connectShow.noDepositOrderCheck()
    } else if (stat == that.data.statVal.noDepositOpen) {
      connectShow.noDepositOpenShow()
    } else if (stat == that.data.statVal.discover) {
      connectShow.discover()
    }
  },
  //错误提示信息确定点击事件
  modalTipClick: function (e) {
    if (e.currentTarget.dataset.mark == 1) {
      wx.setStorageSync("cont_to_rent", 1);
    }
    conTimer.clearConTimer()
    wx.navigateBack({
      delta: 1
    })
  },
  //归还提示的继续租借(继续付租金开锁)
  toContinue: function () {
    this.setData({
      markContinue: true
    })
    // this.getPileState()
    this.sanInfoHandle(this.data.newScanRes, this)
  },
  // // mark: 确认已弹出
  sucOpenConfirm: function () {
    let that = this;
    conTimer.clearConTimer()
    that.data.openLockStat = false; //当前已开锁完毕
    that.data.hasOrderFlg = false;
    console.warn('eqid=>>>', that.data.equId)
    if (!that.data.equId || !that.data.opentime) {
      that.data.equId = wx.getStorageSync('equId');
      that.data.opentime = wx.getStorageSync('opentime');
    }
    wx.redirectTo({
      url: '/pages/index/no_back_tip/no_back_tip?orderCode=' + this.data.orderCode + '&equId=' + this.data.equId,
    })
    // wx.redirectTo({
    //   url: '../../../pages/index/lease_tip/lease_tip?pt=lease&equId=' + that.data.equId + "&opentime=" + that.data.opentime + '&lockType=' + that.data.lockType,
    // })
  },
  // mark: 归还成功提示
  backSuc: function () {
    let that = this
    let data = that.data.backDataInfo
    if (!data || !data.eqId || !data.backTime) {
      console.log("to index--->", data)
      wx.reLaunch({
        url: '../../../pages/index/index',
      })
      return
    }
    wx.navigateTo({
      url: '../../../pages/index/lease_tip/lease_tip?pt=back&equId=' + data.eqId + "&rent=" + data.rent + "&backtime=" + data.backTime + "&opentime=" + data.openTime + "&costtime=" + data.timeLenStr + "&depositBackSuc=" + data.isAutoRefund +
        '&lockType=' + that.data.lockType + '&backSucDesc=' + data.backSucDesc + '&backSucVoiceUrl=' + data.backSucVoiceUrl,
    });
  },
  // mark: 重试开锁
  retry85: function (retryType) {
    var that = this;
    conTimer.start(15)
    connectShow.openLockingShow()
    that.data.canRetry85 = true;
    that.data.hasOrderFlg = false;
    that.data.no_eject_back_flg = null;
    that.data.retryType85 = retryType;
    if (retryType == 'auto') {
      let desc = app.globalData.devConnected ? "蓝牙未断开,开锁失败,重试开锁" : "开锁时蓝牙断开，自动重新连接开锁";
      that.recordBlueConnectError(ConstantData.err_type.data_85_discon_retry, desc + ";gw=" + app.globalData.gatewayUnlockFlg + ";mac=" + that.data.mac);
    } else {
      let desc = app.globalData.devConnected ? "蓝牙未断开,开锁失败,点击重试开锁" : "开锁时蓝牙断开，用户点击重试租借，重新连接";
      that.recordBlueConnectError(ConstantData.err_type.data_85_retry, desc + ";gw=" + app.globalData.gatewayUnlockFlg + ";mac=" + that.data.mac);
    }
    that.clear85Timer();
    BLELocker.stop85Back1Timeout();
    BLELocker.stop85Back2Timeout();
    if (app.globalData.gatewayUnlockFlg === true) {
      //网关开锁
      colonyBlue.openLock(that.data.mac, that);
    } else if (app.globalData.devConnected) {
      that.recordBlueConnectError(ConstantData.err_type.data_85_send, '开始发送85重试:' + app.globalData.devConnected);
      BLELocker.send85Command();
    } else {
      setTimeout(() => {
        if (!that.data.curBlueName) {
          newConUtil.getDevIdAndConnect(that.data.qrc, that.data.type);
        } else {
          newConUtil.connectBLEDevice(that.data.curBlueName);
        }
      }, 800)
    }
  },
  //校验蓝牙权限是否开启,true 开启，false未开启
  validateBleAuth: function () {
    let that = this
    //判断是否蓝牙优先
    if (that.data.isGatewayFirstCon) {
      //可使用网关，不需要蓝牙权限判断
      that.recordBlueConnectError(ConstantData.err_type.gateway_no_auth_ble, '网关不需要校验蓝牙权限');
      return true
    }
    //校验蓝牙权限
    let isAuth = commonUtil.validateOnlyBleAuth((auth) => {
      if (auth == 'mini_ble') {
        if (that.data.auth_mini_ble_flg == true) {
          return
        }
        that.data.auth_mini_ble_flg = true
        console.log('auth_ble_reload:', that.data.clickLeaseBtn)
        //授权成功，显示收费规则
        if (that.data.clickLeaseBtn == 'deposit') {
          leaseShow.chargeRuleShow()
          that.toPayDeposit()
          that.data.avoidorpay = ''
        } else if (that.data.clickLeaseBtn == 'nodeposit') {
          leaseShow.chargeRuleShow()
          wx.showModal({
            title: '是否继续免押租借？',
            content: '',
            complete: (res) => {
              if (res.cancel) {

              }
              if (res.confirm) {
                that.toNoDepositLease()
              }
            }
          })
          that.data.avoidorpay = ''
        } else if (that.data.isScanBack == 'true') {
          that.scanBackManual()
        } else {
          leaseShow.chargeRuleShow()
        }
      }
    })
    console.log("蓝牙权限校验结果:", isAuth)
    that.data.auth_ble = isAuth
    if (isAuth == 'sys_ble_android') {
      //系统蓝牙未打开跳转到对应页面
      bleAuthShow.showAndroidToSettingBle()
      return false
    } else if (isAuth == 'sys_ble_ios') {
      bleAuthShow.showIosSetBleTip()
      return false
    } else if (isAuth == 'wx_ble') {
      bleAuthShow.showAppBleSetting()
      return false
    } else if (isAuth == 'mini_ble') {
      if (that.data.auth_mini_ble_flg == true) {
        return true
      }
      bleAuthShow.showBleMiniToSet()
      return false
    }
    return true
  },

  //工作人或已支付押金的直接租借
  toWorkerLease: function (e) {
    let that = this
    that.data.isWXScore = 0
    newConUtil.leaseEquipment(true)
    that.recordBlueConnectError(ConstantData.err_type.open_lock_worker_lease, '工作人员租借');
  },
  //去免押租赁
  toNoDepositLease: function (e) {
    let that = this
    that.data.clickLeaseBtn = 'nodeposit'
    //验证登录
    var nophone = app.getUserLoginNoPhone();
    if (nophone == null || nophone == undefined || nophone == 1) {
      that.setData({
        avoidorpay: 'avoid'
      })
      that.toWxLogin()
      return
    }

    //校验蓝牙是否开启
    if (!that.validateBleAuth()) {
      that.data.avoidorpay = 'nodeposit_ble'
      //蓝牙未开启，提示用户开启蓝牙
      that.recordBlueConnectError(ConstantData.err_type.deposit_no_ble, '免押前蓝牙未打开,提示打开蓝牙');
      return
    }

    if (app.globalData.devConnected) {
      that.data.isAllowNoDeposit = true
      newConUtil.leaseEquipment()
    } else {
      newConUtil.connectBox(that)
    }

    that.toOpenLock = () => {
      that.data.bleDepositPaySuc = false
      that.data.isWXScore = 1
      that.data.pileState = 1
      that.data.isScanBack = 'false'
      that.data.curContIsBle = false
      that.openLock()
    }
  },
  //去支付押金 
  toPayDeposit: function (event) {
    var that = this
    that.data.clickLeaseBtn = 'deposit'
    that.data.isScanBack = 'false'
    that.data.curContIsBle = false
    that.data.pileState = 1

    //验证登录
    var nophone = app.getUserLoginNoPhone();
    if (nophone == null || nophone == undefined || nophone == 1) {
      that.setData({
        avoidorpay: 'pay'
      })
      that.toWxLogin()
      return
    }

    //校验蓝牙是否开启
    if (!that.validateBleAuth()) {
      that.data.avoidorpay = 'pay_ble'
      //蓝牙未开启，提示用户开启蓝牙
      that.recordBlueConnectError(ConstantData.err_type.deposit_no_ble, '交押金前蓝牙未打开,提示打开蓝牙');
      return
    }

    if (!that.data.read) {
      wx.showToast({
        title: '请勾选我已阅读'
      })
      return
    }
    if (!this.data.payDepositBtnStatus) {
      that.recordBlueConnectError(ConstantData.err_type.deposit_pay_active, '押金支付按钮防呆限制');
      wx.showToast({
        title: '请稍等,或重新扫码',
      })
      return;
    }

    if (app.globalData.devConnected) {
      newConUtil.toPayDeposit()
    } else {
      newConUtil.connectBox(that)
    }

  },

  payDepositSuccess() {
    var that = this

    if (that.data.checkPayStatusInterval) {
      clearInterval(that.data.checkPayStatusInterval);
    }
    that.setData({
      checkPayStatusInterval: null,
    });

    that.recordBlueConnectError(ConstantData.err_type.deposit_pay_confirm, "[押金]支付成功")
    that.getSubscribeMessage('押金支付成功', function () {
      connectShow.payDepositOpenShow()
      wx.setStorageSync("no_pay_deposit", 0);
      that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success, '押金支付成功,准备开锁...');
      if (that.data.noDepositFail) {
        that.setData({
          noDepositFail: false
        })
      }

      if (that.data.isColonyCon) {
        //网关开锁前标记的时间点，判断断开时校验时间，如果超过30秒，则认为标记失效进行断开
        app.globalData.gatewayUnlockFlgTime = new Date().getTime();
        that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]gateway开始直接开锁-押金支付成功");
        newConUtil.leaseEquipment(true);
        return;
      }

      //判断是否还在连接，连接着的直接开锁进行租赁
      wx.getConnectedBluetoothDevices({
        services: ['FEE7'],
        success: function (res) {
          console.log("111----current connected blue " + JSON.stringify(res))
          if (res.devices && res.devices.length > 0) {
            //展示收费规则提示框
            that.setData({
              payDepositStat: true,
              showModalStatus: false,
              mapShowStatus: false,
              hideIsDisconnectStat: false,
              bindUserListStatus: false,
              agentLeaseSelStatus: false,
              isPayDeposit: true
            })
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]开始直接开锁-押金支付成功");
            newConUtil.leaseEquipment(true);
          } else {
            that.data.bleDepositPaySuc = true;
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_connect, "[连接]没有设备,重新连接-押金支付成功")
            connectCurrentBlue(that)
          }
        },
        fail: function (err) {
          console.log('获取蓝牙连接失败：', err)
          that.data.bleDepositPaySuc = true;
          that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_reconnect, "[连接]获取失败,重新连接-押金支付成功")
          connectCurrentBlue(that)
        }
      })
    });
  },

  toPay: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode);
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    app.toPayValideLogin(orderCode, function (loginCode, orderCode, err) {

      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },

          success: function (res) {
            let netErr = app.handleRes(res, that);
            if (netErr) {
              return
            }
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              leaseShow.resultShow(data.description ? data.description : '押金支付失败')
              that.recordBlueConnectError(ConstantData.err_type.deposit_pay_fail, '押金支付请求失败')
              return
            }

            app.globalData.isOpenLock = true;
            that.setData({
              hideIsDisconnectStat: false, //支付成功后隐藏不关闭蓝牙
              openning_show: true, //200114 冯慧敏，押金支付之前就显示开锁中，以防止押金支付成功后用户有机会再次点击扫码，影响开锁
              openning_desc: '正在支付押金...',
            })

            if (that.data.checkPayStatusInterval) {
              clearInterval(that.data.checkPayStatusInterval);
            }
            that.data.isPayDepositSuccess = false;
            that.data.checkPayStatusInterval = setInterval(() => {
              console.log('【轮询押金支付状态】');
              if (that.data.isPayDepositSuccess) {
                clearInterval(that.data.checkPayStatusInterval);
                that.data.checkPayStatusInterval = null
                return;
              }

              noDepositLease.queryPayDepositStatus(orderCode).then(res => {
                console.log('【押金支付状态查询】已支付...' + res);
                that.data.isPayDepositSuccess = true;
                if (that.data.pileState == 1) {
                  that.setData({
                    paymentMark: 1
                  })
                }
                newConUtil.getDevIdAndConnect(that.data.qrc, that.data.type);
                clearInterval(that.data.checkPayStatusInterval)
              }).catch(error => {
                console.log('【押金支付状态查询】未支付...' + error);
              })

            }, 1000);

            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log('已付押金----', that.data.isPayDepositSuccess, that.data.pileState, res)
                if (that.data.isPayDepositSuccess) {
                  that.getSubscribeMessage('押金支付成功', null);
                  return;
                }
                if (that.data.pileState == 1) {
                  that.setData({
                    paymentMark: 1
                  })
                } else if (that.data.pileState == 0) {
                  that.payDepositSuccess();
                }
              },
              fail: function (res) {
                app.globalData.isOpenLock = false;
                that.recordBlueConnectError(ConstantData.err_type.deposit_pay_cancel, "押金FAIL:" + JSON.stringify(res))
                that.setData({
                  openning_show: false,
                  hideIsDisconnectStat: false,
                  payDepositBtnStatus: true,
                  payDepositBtnTxt: "去缴纳"
                })
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'index2-' + JSON.stringify(res) : '');

                if (that.data.checkPayStatusInterval) {
                  clearInterval(that.data.checkPayStatusInterval);
                }
              },
              complete: function (res) {
                getApp().hideLoading()
                that.setData({
                  hideIsDisconnectStat: false,
                  payDepositBtnStatus: true,
                  payDepositBtnTxt: "去缴纳"
                })
                console.log("complete--" + data.data.paySign)
                console.log(res)

                if (that.data.checkPayStatusInterval) {
                  clearInterval(that.data.checkPayStatusInterval);
                }
              }
            })


          },
        })

      })

    });

  },

  getSubscribeMessage: function (text, callback) {
    if (wx.requestSubscribeMessage) {
      console.log('【订阅消息】支持弹出订阅消息...')
      let tmplIds = ['KnUsFuS2NB07Pf9xbznQlyK_qZOU7DxOFl8l6E26Nww', '-S91jtVpX2Vto5EyXauKW008LYSSbsZiI8IWdepDarE'];
      let acceptIds = [];
      wx.requestSubscribeMessage({
        tmplIds: tmplIds,
        success(res) {
          console.log('【订阅消息】弹出订阅消息成功...' + JSON.stringify(res))
          let acceptIds = [];
          for (let i = 0; i < tmplIds.length; i++) {
            res[tmplIds[i]] == 'accept' ? acceptIds[i] = 1 : acceptIds[i] = 0;
          }
          app.executeRequest((header) => {
            wx.request({
              url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/wx_sub_msg',
              method: 'post',
              header: header,
              data: {
                acceptIds: JSON.stringify(acceptIds)
              }
            })
          })
        },
        fail(error) {
          console.log('【订阅消息】弹出订阅消息失败...' + JSON.stringify(error))
        },
        complete(res) {
          console.warn('【订阅消息】弹出订阅消息完成...' + text, res, acceptIds);
          if (callback) {
            callback();
          }
        }
      })
    } else {
      console.log('【订阅消息】不支持弹出订阅消息...')
      if (callback) {
        callback();
      }
    }
  },
  //其他页面调用失败信息
  showFailTip: function () {
    bleFailShow.modalMsgShow()
  },

  switchRulesShow() {
    this.setData({
      showRules: !this.data.showRules
    })
  },

  /**
   * 选择包时卡绑定账号的变更
   */
  bindUserChange: function (e) {
    var val = e.detail.value
    var user = this.data.bindUserList[val[0]]

    console.warn(user)

    if (!user.bindUid) {
      wx.showToast({
        title: '请重新选择',
      })
      return
    }

    this.setData({
      user_tab: user.bindTag,
      selBindUserId: user.bindUid,
      checkboxStatus: 'checkboxSelected',
      selBindUser: user
    })
  },
  /**
   * 绑定包时卡的账号确定开锁
   */
  bindUserChangeSure: function () {
    if (this.data.selBindUserId == 0) {
      this.setData({
        selBindUserId: this.data.bindUserList[0].bindUid,
        selBindUser: this.data.bindUserList[0]
      })
    }

    this.setData({
      agentLeaseSelStatus: false,
      isPayDeposit: true,
    })

    var selBindUid = this.data.selBindUserId
    console.log("代租赁,开始开锁------")
    console.log(selBindUid)

    this.openLock()
  },
  /**
   * 绑定包时卡账号取消选择
   */
  cancelAgentLease: function () {
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index1032')
    this.setData({
      agentLeaseSelStatus: false,
      bindUserListStatus: false,
      mapShowStatus: true,
    })
  },
  /**
   * 确定租赁
   */
  sureToAgentLease: function () {
    this.setData({
      cancelAgentSelLeaseStatus: false,
      isPayDeposit: true
    })

    var that = this
    var selBindUid = this.data.selBindUserId
    var selUser = this.data.selBindUser
    if (selBindUid == 0) {
      selUser = this.data.bindUserList[0]
    }
    //绑定类型2爱心租赁，1包时卡租赁
    var bindType = 1
    var timeLenStr = ''
    if (selUser.employerUid) {
      //爱心租赁的
      bindType = 2
    } else {
      //绑卡代租的
      bindType = 1
    }

    var eqTid = this.data.wxEqTid
    console.log("确认完选择的代租用户--" + eqTid + "," + selUser.bindUid)
    this.validateBindNoPayOrNoReturn(selUser, eqTid, bindType)
  },
  /**
   * 校验包时卡或门诊爱心租赁是否存在未支付或未归还的
   */
  validateBindNoPayOrNoReturn: function (selUser, eqTid, bindType) {
    var that = this

    var cardTimeLen = selUser.cardTimeLen
    var timeLenStr = this.data.leftTimeLenStr
    var noPayStrSuffix = ''
    if (bindType == 1) {
      //包时卡的时长信息
      timeLenStr = selUser.bindPhone + '(' + selUser.bindTag + '),剩余时长:'
      if (cardTimeLen < 60) {
        timeLenStr += cardTimeLen + '分钟'
      } else {
        timeLenStr += parseInt(cardTimeLen / 60) + '小时'
      }

      noPayStrSuffix = ',请电话告知用户购买包时卡后才能再借用!'
    } else if (bindType == 2) {
      noPayStrSuffix = ',请完成支付再租借!'
    }

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/nopay',
        method: 'post',
        header: header,
        data: {
          buid: selUser.bindUid,
          tid: eqTid,
          bindType: bindType
        },
        success: function (res) {
          console.log(res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          var result = res.data.data
          var noPayTimeLen = result.noPayTimeLen
          var noReturnCount = result.noReturnCount
          var depositPayRst = result.depositPayRst
          var cardTimeLen = result.cardTimeLen
          var noReturnEquId = result.noReturnEquId
          var equTypeName = result.equTypeName
          var isCouldLease = true
          var noPayTipStatus = false
          var noPayTimeLenStr = ''
          var noLeaseTipInfo = ''
          if (cardTimeLen <= 0 && bindType == 1) {
            //包时卡时间不足
            isCouldLease = false
            noPayTipStatus = true
            noLeaseTipInfo = '包时卡已用完，不能为他(代租)，请电话通知家属购买包时卡'
          } else if (depositPayRst <= 0) {
            //未交押金
            isCouldLease = false
            noPayTipStatus = true
            noLeaseTipInfo = '该用户押金还未支付,不能租借'
          } else if (noReturnEquId > 0) {
            //存在未归还设备
            noLeaseTipInfo = '该用户有租借的' + noReturnEquId + '号' + equTypeName + '没有归还,不能租借'
            isCouldLease = false
            noPayTipStatus = true
          } else if (noPayTimeLen && noPayTimeLen > 0) {
            //存在未支付的订单
            isCouldLease = false
            noPayTipStatus = true
            if (noPayTimeLen < 60) {
              noPayTimeLenStr = noPayTimeLen + '分钟'
            } else {
              noPayTimeLenStr = parseInt(noPayTimeLen / 60) + '小时'
            }
            noLeaseTipInfo = '该用户已欠费(有' + noPayTimeLenStr + '时长未付款)' + noPayStrSuffix
          } else {
            //可以正常租赁
          }

          that.setData({
            selBindUserId: selUser.bindUid,
            user_tab: selUser.bindTag,
            leftTimeLenStr: timeLenStr,
            agentLeaseSelStatus: true,
            showModalStatus: false,
            bindUserListStatus: false,
            mapShowStatus: false,
            leaseBtnStatus: isCouldLease,
            noPayTimeTipStatus: noPayTipStatus,
            noPayTimeLenStr: noPayTimeLenStr,
            noLeaseTipInfo: noLeaseTipInfo
          })
        },
        fail: function (res) {
          wx.showToast({
            title: '稍后重试',
          })
        }
      })

    })

  },
  goUserLease: function () {
    wx.navigateTo({
      url: '/pages/user_record/lease/user_lease',
    })
  },
  /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function () {
    app.goFollowMp(-200002, '关注公众号-我的')
  },
  /**
   * 继续租借
   */
  continueToLease() {
    var that = this;
    //继续租赁   
    //将结果值改为正常，用户继续租赁
    that.data.conDevRes.data.rst = 0
    //处理返回数据并调用蓝牙连接
    that.handleConDevRes()
  },
  toWxLogin: function () {
    wx.navigateTo({
      url: '/pages/wx-login/wx-login',
    });
  },
  /**
   * 网络异常
   */
  networkFail() { // mark: 网络断开提示
    BLELocker.disconnect('networkFail3676');
    leaseShow.netFail("网络断开，请检查网络后，重新扫码")
  },

  /**
   * 重新扫码
   */
  reScan: function () {
    let that = this
    that.data.bleDepositPaySuc = false;

    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        that.data.isWxScanFlg = false;
        var qrc = '';
        var qrCode = res.result;
        if (!qrCode) {
          wx.showToast({
            title: '二维码为空',
          })
          that.recordBlueConnectError(ConstantData.err_type.qrc_null, "二维码为空,qrc=" + qrCode)
          that.data.scanningCode = false;
          return;
        }
        let macReg = /[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
        let isMacAddr = macReg.test(qrCode);
        if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_URL_PREFIX) == 0 || isMacAddr) {
          //设备二维码
          let qrc_old = app.getScanQrcContent();
          that.data.qrcContent = qrCode;
          if (isMacAddr) {
            qrc = qrCode.replace(/:/g, "");
          } else {
            var rst = qrCode.split('/');
            qrc = rst[rst.length - 1];
            that.data.qrc = qrc;
          }
          app.globalData.scan.qrc = qrc;
          try {
            wx.setStorageSync('scan_qrc', qrc);
          } catch (e) {}
          if (qrc != qrc_old) {
            wx.removeStorageSync('blue_fail_time')
            wx.removeStorageSync('rfid_error_time')
            wx.removeStorageSync('insert_fail_time')
            wx.removeStorageSync('hook_fail_time')
            wx.removeStorageSync('has_opened_gprs')
            wx.removeStorageSync('no_eject_times')
          }
        } else {
          leaseShow.resultShow('二维码扫描异常，请换一个桩租赁');
          that.data.scanningCode = false;
          that.recordBlueConnectError(ConstantData.err_type.qrc_err, "二维码有误,qrc=" + qrCode)
          return
        }
        console.log("scan-----------qrc=" + qrc)
        console.log("******获取要连接的设备名称", app.globalData.conTimeoutTimer, !null);
        that.data.qrc = qrc;
        that.data.isScanBack = false
        that.getPileState()
      },
      fail: function (res) {
        that.data.scanningCode = false;
        that.setData({
          loading_show: false
        })
        that.data.qrcContent = '';
        that.recordBlueConnectError(ConstantData.err_type.qrc_cancel, "调用微信扫码失败或取消")
      }
    });

  },

  // mark: 重新连接
  retryConnect: function () {
    connectShow.reday()
    newConUtil.connectBLEDevice(this.data.curBlueName);
  },

  //记录归位桩蓝牙连接错误日志
  recordBlueConnectError: function (errType, errDesc, tag) {
    var that = this
    let nowTime = util.formatTime(new Date()) + '-----';
    var miniVer = ConstantData.CONSTATNT_DATA.MINI_VERSION
    let authStr = systemInfo ? (systemInfo.locationAuthorized + ',' + systemInfo.bluetoothEnabled + ',' + systemInfo.locationEnabled + ',' + systemInfo.wifiEnabled) : 'null'
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/error/bc',
        method: 'post',
        header: header,
        data: {
          homingPileBlueName: that.data.curBlueName, //归位桩的蓝牙名称,最长100个字
          phoneOs: systemInfo.system, //手机系统信息,最长245
          phoneFactory: systemInfo.model, //手机厂商,最长245
          phoneType: systemInfo.model || systemInfo.brand, //手机型号,最长245
          weixinVer: systemInfo.version + ',' + baseVer + ',' + miniVer, //微信版本号,最长45
          errType: errType ? parseInt((errType + '').replace(/[^0-9]/ig, '')) : -1, //错误类型,最大值127；1.搜索,2.连接,3.auth,4.init 5. 95 6. 85
          errDesc: nowTime + '[' + authStr + ']' + ',' + errDesc + ',', //错误描述,最长545
          tag: tag && tag != 'undefined' ? tag : ''
        },
        success: function (res) {
          console.log("recordErrSuc", res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          // console.log("蓝牙连接错误日志记录成功", errDesc);
        },
        fail: function (res) {
          // console.log("蓝牙连接错误日志记录失败")
          console.log("recordErrFail", res)
        }
      })
    })
  },
  openDepReason: function () {
    this.setData({
      depositPop: true
    })
  },
  closeDepReason: function () {
    this.setData({
      depositPop: false
    })
  },
  //客服中心
  toService: function () {
    wx.switchTab({
      url: '/pages/servicer/index'
    })
  },
  //故障上报
  tofault: function () {
    wx.navigateTo({
      url: '/pkgNew/pages/faultReporting/index',
    })
  },
  //查看订单
  toOrderDetail: function () {
    wx.navigateTo({
      url: '/pages/user_record/lease/user_lease'
    })
  },
})

//租赁相关的展示提示
var leaseShow = { // mark: 租借信息展示对象
  //页面数据操作对象 
  pageThat: null,
  //收费规则
  chargeRuleShow: function () {
    let freeTimeTipContent = this.pageThat.data.leftFreeTimeTipContent
    let ruleTip = (!this.pageThat.data.showFreeTipFlg) && freeTimeTipContent && (!this.pageThat.data.isWorker)
    this.pageThat.data.showFreeTipFlg = true
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: true,
      showStat: {
        rule: true
      },
      leftFreeTimeTipContent: freeTimeTipContent,
      showFreeTipDialog: ruleTip
    })
    console.log("showFreeTipDialog-->", this.pageThat.data.showFreeTipDialog, this.pageThat.data.showFreeTipFlg, !this.pageThat.data.showFreeTipFlg, ruleTip)
  },
  //开锁成功显示
  openSucShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        leasesuc: true
      }
    })
  },
  //开锁失败显示
  openFailShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        failTip: true
      }
    })
  },
  //归还成功显示
  backSucShow: function () {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        showReturn: true,
        resultTip: true,
        backSucBtn: true,
        resultDesc: '您已完成归还！',
        resultSecondDesc: '如需要租借点击首页"扫码开锁"按钮',
      }
    })
    //播放归还成功语音
    console.log("播放归还成功语音")
    AudioUtil.play('/image/backSuc.mp3', false)
  },
  //帮归还成功显示
  helpBackSucShow: function () {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        showReturn: true,
        resultTip: true,
        helpBackSucBtn: true,
        resultDesc: '您已帮忙归还成功！',
        resultSecondDesc: '若您需要租借，点击首页"扫码借"按钮',
      }
    })
  },
  //归还失败显示
  backFailShow: function () {

  },
  //用户归还后立马再次租借提醒
  backSucToLeaseTip: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        backSucToLease: true
      }
    })
  },
  //租赁前消息提示
  beforeLeaseTipShow: function (continueLeaseBtnLeft, contintueLeaseBtnName, cancelBtnName, tipContent) {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        beforeLeaseTip: true,
        continueBtnLeft: continueLeaseBtnLeft,
        cancelBtnName: cancelBtnName,
        continueBtnName: contintueLeaseBtnName,
        tipContent: tipContent
      }
    })
  },
  openLockOverTip: function () {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.data.tipOpenLockOverFlg = true
    console.log("开锁完成广告：", app.globalData.miniBeeConfig, app.globalData.miniBeeConfig.lease_success)
    this.pageThat.setData({
      connectType: '租借',
      showStat: {
        blankBtn: false,
        resultTip: true,
        openOverConfirm: true,
        resultDesc: '开锁完成',
      },
      beeBannerConfig: app.globalData.miniBeeConfig.lease_success
    })
    console.log("开锁完成播报语音")
    //播放租借成功语音
    AudioUtil.play('/image/leaseLinkSuc.mp3', false)
  },
  //结果提示
  resultShow: function (resultDesc) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: false,
      showStat: {
        resultTip: true,
        resultDesc: resultDesc,
        blankBtn: true
      }
    })
  },
  //结果显示取消
  resultHide: function () {
    this.pageThat.setData({
      showStat: {
        resultTip: false
      }
    })
  },

  //网络fail提示
  netFail: function (desc) {
    this.resultShow(desc)
  }
}

//蓝牙权限相关提示
var bleAuthShow = { // mark: 蓝牙授权信息展示对象
  //页面数据操作对象
  pageThat: null,
  //安卓系统蓝牙可跳转到设置页的
  showAndroidToSettingBle: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthAndroidToSet: true
      }
    })
  },
  //安卓系统设置系统蓝牙的方式
  showAndroidSetTip: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthAndroid: true
      }
    })
  },
  //IOS系统设置系统蓝牙的方式
  showIosSetBleTip: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthIos: true
      }
    })
  },
  //安卓系统定位权限配置提示
  showAndroidSysLocationSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        locationAndroidTip: true
      }
    })
  },
  //Ios系统定位权限配置提示
  showIosSysLocationSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        locationIosTip: true
      }
    })
  },
  //IOS的app蓝牙配置项
  showAppBleSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthAppToSet: true
      }
    })
  },
  //Ios应用定位权限配置提示
  showAppLocationSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        locationAuthAppToSet: true
      }
    })
  },

  //小程序蓝牙权限未授权
  showBleMiniToSet: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleMiniAuthToSet: true
      }
    })
  },


}

var connectShow = { // mark: 连接提示信息展示对象
  //页面数据操作对象
  pageThat: null,
  //连接准备开始    
  reday: function () {
    conTimer.start()
    console.warn('连接开始标记====>', this.pageThat.data.showStat)
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showImage: '',
      showStat: {
        connect: true,
        conStatDesc: "连接信息检查中...",
      }
    })
  },
  //蓝牙权限
  checkBle: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "蓝牙权限检查中...",
      }
    })
  },
  //连接开始
  start: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showImage: '',
      showStat: {
        connect: true,
        conStatDesc: "连接中...",
      }
    })
  },
  //搜索中
  discover: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "查找设备中,请稍后...",
      }
    })
  },
  //开启连接
  connect: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "连接成功,数读取中...",
      }
    })
  },
  //连接成功
  successConnect: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        hideLoad: true,
        conStatDesc: "蓝牙连接成功,请点击开锁~",
      }
    })
  },
  //读取数据及解析数据
  read: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "连接成功,数读取中...",
      }
    })
  },
  //免押查询
  noDepositOrderCheck: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "免押信息核对中...",
      },
      leaseBtnShow: false,
    })
  },
  noDepositOpenShow: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "免押授权成功,准备开锁...",
      },
      leaseBtnShow: false,
    })
  },
  payDepositOpenShow: function () {
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "押金支付成功,准备开锁...",
      },
      leaseBtnShow: false,
    })
  },
  //点击租借后页面防呆处理
  clickLeaseFirstShow: function () {
    getApp().hideLoading()
    let leaseType = this.pageThat.data.clickLeaseBtn == 'deposit' ? '支付押金' : '免押'
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showUnlock: false,
      showStat: {
        connect: true,
        conStatDesc: leaseType + "状态检查中...",
      },
      leaseBtnShow: false,
    })
  },
  //开锁中
  openLockingShow: function () {
    // conTimer.start(15)
    getApp().hideLoading()
    // this.pageThat.hideAllShow()
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showUnlock: false,
      showStat: {
        connect: true,
        conStatDesc: "开锁中...",
      },
      leaseBtnShow: false,
    })
  },
  networkConnecting: function () {
    conTimer.start()
    // this.pageThat.hideAllShow()
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    let extParams = this.pageThat.data.conDevExtParams
    let gatewayId = extParams ? "(" + extParams.gatewayId + ")" : ""
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "网关" + gatewayId + "连接中...",
      }
    })
  },
  //接收到95数据开始处理
  handle95Data: function () {
    // this.pageThat.hideAllShow()
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "数据已返回,开始处理...",
      }
    })
  },
  //上报95数据
  getRuleOrBack: function () {
    // this.pageThat.hideAllShow()
    if (!this.pageThat.data.showStat.connect) {
      this.pageThat.hideAllShow()
    }
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "请稍等,处理数据中...",
      }
    })
  }
}

//蓝牙连接过程失败
var bleFailShow = {
  //页面数据操作对象
  pageThat: null,
  showMsg: function (msg) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: false,
      showStat: {
        connect: true,
        msg: msg,
      }
    })
  },
  modalMsgShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: false
    })
    conTimer.clearConTimer()
  },
  openFailTipShow: function (errType) {
    this.modalMsgShow()
    let pile_id = this.pageThat.data.pile_id ? 'Z' + this.pageThat.data.pile_id : this.pageThat.data.equId;
    this.pageThat.setData({
      modal: {
        modal_show: true,
        desc: '1、如未弹出，请点击“重试租借”再租借一次，\n2、如已弹出，请点击“设备已弹出”。\n3、请慎重选择，如果不做操作，我们将默认为设备已弹出。',
        desc_mini: pile_id + '-' + (errType ? errType : ''),
        desc_center: false,
        sucOpen: true,
        retry85: true
      }
    })
  }
}
// mark: 连接计时器
var conTimer = {
  //页面数据操作对象
  pageThat: null,
  conTimeCount: null,
  start: function (seconds) {
    let pthat = this.pageThat
    let conThat = this
    console.log("连接倒计时定时器-start-->", seconds);
    pthat.setData({
      conLeftSeconds: seconds ? seconds : 60
    });
    if (this.conTimeCount != null) {
      clearInterval(this.conTimeCount);
    }
    this.conTimeCount = setInterval(() => {
      let leftSecond = pthat.data.conLeftSeconds - 1;
      console.log("connnect -->leftSecond=", leftSecond);
      if (leftSecond <= 0) {
        clearInterval(conThat.conTimeCount);
        //倒计时结束未连接成功
        BLELocker.disconnect('condev4108');
        if (pthat.data.curContIsBle) {
          leaseShow.resultShow("连接超时，请重新扫码租借")
        }
      } else {
        pthat.setData({
          conLeftSeconds: leftSecond
        });
        if (pthat.data.curContIsBle && leftSecond < 35) {
          //检查当前权限是否存在异常，导致超时
          pthat.bleConAuthCheck(false)
        }
      }
    }, 1000);
  },
  //清空连接的计时器
  clearConTimer: function () {
    this.pageThat.setData({
      conLeftSeconds: 0
    })
    clearInterval(this.conTimeCount);
    if (app.globalData.conTimeoutTimer) {
      clearTimeout(app.globalData.conTimeoutTimer)
    }
    if (app.globalData.scanEquTimer) {
      clearTimeout(app.globalData.scanEquTimer)
    }
  },


}

function connectCurrentBlue(that) {
  console.log("开始蓝牙连接：", that.data.curBlueName)
  //隐藏可以关闭蓝牙
  that.data.hideIsDisconnectStat = true;
  if (that.data.curBlueName) {
    connectShow.reday()
    newConUtil.connectBLEDevice(that.data.curBlueName)
  } else {
    leaseShow.resultShow('请重新扫码!')
  }
}

function loginAuth(that) {
  //调用登录接口
  wx.login({
    success: function (res) {
      console.log(res);
      if (res.code) {
        //发起网络请求
        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/login',
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          data: {
            code: res.code,
          },
          success: function (res) {
            if (!res.statusCode) {
              return;
            }
            let netErr = app.handleRes(res, that);
            if (netErr) {
              return
            }

            var result = res.data.result;
            if (result == 0) {
              try {
                wx.setStorageSync('pass', res.data.data.pass);
                wx.setStorageSync('temp', res.data.data.temp);
                wx.setStorageSync('ltime', res.data.data.ltime);
                wx.setStorageSync('cpass', res.data.data.cpass);
                wx.setStorageSync('uuid', res.data.data.uuid);
                wx.setStorageSync('nophone', res.data.data.nophone);
                wx.setStorageSync('isGetUserPhone', res.data.data.adminUserPhone);
                wx.removeStorageSync('exitLogin')
              } catch (e) {}
            } else {
              wx.showToast({
                title: res.data.description
              });
            }
          }
        })
      } else {
        console.log('获取用户登录态失败！' + res.errMsg)
      }
    }
  });

}